package com.sau.pixelcart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sau.pixelcart.common.constant.ProductConstant;
import com.sau.pixelcart.common.exception.BusinessException;
import com.sau.pixelcart.common.result.PageResult;
import com.sau.pixelcart.domain.dto.ProductDTO;
import com.sau.pixelcart.domain.dto.ProductPageDTO;
import com.sau.pixelcart.domain.entity.Category;
import com.sau.pixelcart.domain.entity.Product;
import com.sau.pixelcart.domain.entity.ProductInventory;
import com.sau.pixelcart.domain.vo.ProductVO;
import com.sau.pixelcart.mapper.CategoryMapper;
import com.sau.pixelcart.mapper.ProductInventoryMapper;
import com.sau.pixelcart.mapper.ProductMapper;
import com.sau.pixelcart.mapper.UserMapper;
import com.sau.pixelcart.service.ICategoryService;
import com.sau.pixelcart.service.IInventoryAlertService;
import com.sau.pixelcart.service.IProductInventoryService;
import com.sau.pixelcart.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品核心信息表 服务实现类
 * </p>
 *
 * @author Inton
 * @since 2025-03-08
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private IProductInventoryService productInventoryService;

    @Autowired
    private ProductInventoryMapper productInventoryMapper;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IInventoryAlertService inventoryAlertService;

    /**
     * 添加/修改商品
     *
     * @param productDTO
     * @return
     */
    @Transactional
    @Override
    public String save(ProductDTO productDTO) {
        //判断所选分类是否存在（二层保障）
        String categoryId = productDTO.getCategoryId();
        Category category = categoryMapper.selectById(categoryId);
        if (category == null) {
            throw new BusinessException("所选分类信息不存在");
        }
        //判断DTO中是否有id信息，没有id进行添加操作，有id进行修改操作
        if(productDTO.getId() == null || productDTO.getId().isEmpty()){

            //判断商品表中是否有该商品信息（name是否重复）
            String productName = productDTO.getName();
            LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
            productWrapper.eq(Product::getName, productName);
            Product product = productMapper.selectOne(productWrapper);
            if (product != null) {
                throw new BusinessException("商品信息已存在");
            }
            //添加到product表
            Product newProduct = new Product();
            BeanUtils.copyProperties(productDTO,newProduct);
            newProduct.setCreatedTime(LocalDateTime.now());
            newProduct.setUpdatedTime(LocalDateTime.now());
            productMapper.insert(newProduct);
            //添加到库存表
            ProductInventory productInventory = new ProductInventory();
            BeanUtils.copyProperties(productDTO,productInventory);
            productInventory.setProductId(newProduct.getId());
            productInventory.setStock(productDTO.getStock());
            productInventory.setLowStockThreshold(ProductConstant.LOW_STOCK_NUM);
            productInventory.setLastUpdated(LocalDateTime.now());
            productInventoryService.save(productInventory);

            //是否触发库存预警
            inventoryAlertService.checkStockWarning(productInventory.getProductId());

        }else{
            //修改操作
            Product updateProduct = new Product();
            BeanUtils.copyProperties(productDTO,updateProduct);
            updateProduct.setUpdatedTime(LocalDateTime.now());
            productMapper.updateById(updateProduct);

        }
        return productDTO.getId();
    }

    /**
     * 获取商品详情
     *
     * @param productId
     * @return
     */
    @Override
    public ProductVO getProductById(String productId) {
        //根据id获取商品信息
        Product product = productMapper.selectById(productId);
        ProductVO productVO = new ProductVO();
        BeanUtils.copyProperties(product,productVO);
        return productVO;
    }

    /**
     * 商品分页查询
     * @param productPageDTO
     * @return
     */
    @Override
    public PageResult<ProductVO> pageQuery(ProductPageDTO productPageDTO) {
        Page<Product> pageParam = new Page<>(productPageDTO.getPage(),productPageDTO.getPageSize());
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        if(productPageDTO.getStatus() != null){
            wrapper.eq(Product::getStatus, productPageDTO.getStatus());
        }
        if(productPageDTO.getCategoryId() != null){
            wrapper.eq(Product::getCategoryId, productPageDTO.getCategoryId());
        }
        if(productPageDTO.getKeyword() != null && !productPageDTO.getKeyword().equals("")){
            wrapper.like(Product::getCode, productPageDTO.getKeyword())
                    .or()
                    .like(Product::getName, productPageDTO.getKeyword());
        }

        //执行分页查询
        Page<Product> page = productMapper.selectPage(pageParam, wrapper);

        //查询库存数量和版本
        List<ProductInventory> productInventoryList = productInventoryService.list();
        Map<String, ProductInventory> productInventoryMap = productInventoryList.stream().collect(Collectors.toMap(ProductInventory::getProductId, Function.identity()));

        //查询分类名称
        List<Category> categoryList = categoryService.list();
        Map<String, String> categoryMap = categoryList.stream().collect(Collectors.toMap(Category::getId, Category::getName));

        //转换成VO
        List<ProductVO> productVOList = page.getRecords().stream().map(product -> {
            ProductVO productVO = new ProductVO();
            BeanUtils.copyProperties(product, productVO);
            //补充分类名称
            productVO.setCategory(categoryMap.get(product.getCategoryId()));
            productVO.setStock(productInventoryMap.get(product.getId()).getStock());
            productVO.setVersion(productInventoryMap.get(product.getId()).getVersion());
            return productVO;
        }).collect(Collectors.toList());

        PageResult<ProductVO> pageResult = new PageResult<>();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(productVOList);
        return pageResult;

    }

    /**
     * 修改商品状态
     *
     * @param productDTO
     */
    @Override
    public void changeStatus(ProductDTO productDTO) {
        String id = productDTO.getId();
        String status = productDTO.getStatus();
        productMapper.changeStatus(id,status);
    }

    /**
     * 删除商品
     * @param productId
     */
    @Override
    @Transactional
    public void deleteById(String productId) {
        //删除商品表
        productMapper.deleteById(productId);
        //删除库存表
        productInventoryMapper.deleteByProductId(productId);
    }


}
